﻿using DTcms.Common;
using DTcms.SMS;
using DTcms.Web.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Http;

namespace DTcms.Web.MvHtml.Controllers
{
    /// <summary>
    /// 需要授权API接口
    /// </summary>
    [UserValidate(IsLogin = true)]
    [ModelStateFilter]
    public class Lisence_AjaxController : WebApiController
    {
        #region 检查用户是否登录
        [HttpGet]
        public IHttpActionResult user_check_login()
        {
            //检查用户是否登录
            if (userModel == null)
            {
                return Json(new { status = 0, username = "匿名用户！" });
            }
            return Json(new { status = 1, username = userModel.user_name });
        }
        #endregion
        #region 修改用户信息
        [HttpPost]
        public IHttpActionResult user_info_edit()
        {
            string nick_name = Utils.ToHtml(DTRequest.GetFormString("txtNickName"));
            string sex = DTRequest.GetFormString("rblSex");
            string birthday = DTRequest.GetFormString("txtBirthday");
            string email = Utils.ToHtml(DTRequest.GetFormString("txtEmail"));
            string mobile = Utils.ToHtml(DTRequest.GetFormString("txtMobile"));
            string telphone = Utils.ToHtml(DTRequest.GetFormString("txtTelphone"));
            string qq = Utils.ToHtml(DTRequest.GetFormString("txtQQ"));
            string msn = Utils.ToHtml(DTRequest.GetFormString("txtMsn"));
            string province = Utils.ToHtml(DTRequest.GetFormString("txtProvince"));
            string city = Utils.ToHtml(DTRequest.GetFormString("txtCity"));
            string area = Utils.ToHtml(DTRequest.GetFormString("txtArea"));
            string address = Utils.ToHtml(DTRequest.GetFormString("txtAddress"));
            string signature = Utils.ToHtml(DTRequest.GetFormString("txtSignature"));
            //检查昵称
            if (string.IsNullOrEmpty(nick_name))
            {
                return Json(new { status = 0, msg = "对不起，请输入您的姓名昵称！" });
            }
            //检查省市区
            if (string.IsNullOrEmpty(province) || string.IsNullOrEmpty(city) || string.IsNullOrEmpty(area))
            {
                return Json(new { status = 0, msg = "对不起，请选择您所在的省市区！" });
            }
            BLL.users bll = new BLL.users();
            //检查手机，如开启手机注册或使用手机登录需要检查
            if (userConfig.regstatus == 2 || userConfig.mobilelogin == 1)
            {
                if (string.IsNullOrEmpty(mobile))
                {
                    return Json(new { status = 0, msg = "对不起，请输入您的手机号码！" });
                }
                if (userModel.mobile != mobile && bll.ExistsMobile(mobile))
                {
                    return Json(new { status = 0, msg = "对不起，该手机号码已被使用！" });
                }
            }
            //检查邮箱，如开启邮箱注册或使用邮箱登录需要检查
            if (userConfig.regstatus == 3 || userConfig.emaillogin == 1)
            {
                if (string.IsNullOrEmpty(email))
                {
                    return Json(new { status = 0, msg = "对不起，请输入您的电子邮箱！" });
                }
                if (userModel.email != email && bll.ExistsEmail(email))
                {
                    return Json(new { status = 0, msg = "对不起，该电子邮箱已被使用！" });
                }
            }

            //开始写入数据库
            userModel.nick_name = nick_name;
            userModel.sex = sex;
            DateTime _birthday;
            if (DateTime.TryParse(birthday, out _birthday))
            {
                userModel.birthday = _birthday;
            }
            userModel.email = email;
            userModel.mobile = mobile;
            userModel.telphone = telphone;
            userModel.qq = qq;
            userModel.msn = msn;
            userModel.area = province + "," + city + "," + area;
            userModel.address = address;
            userModel.signature = signature;

            bll.Update(userModel);
            return Json(new { status = 1, msg = "账户资料已修改成功！" });
        }
        #endregion
        #region 确认裁剪用户头像
        [HttpPost]
        public IHttpActionResult user_avatar_crop(string data)
        {
            string avatar = string.Empty;
            //检查参数
            if (data.Length == 0)
            {
                return Json(new { status = 0, msg = "对不起，请先上传一张图片！" });
            }
            //取得保存的新文件名
            UpLoad upFiles = new UpLoad();
            bool result = upFiles.base64Image(data, out avatar);
            if (!result)
            {
                return Json(new { status = 0, msg = "图片裁剪过程中发生意外错误！" });
            }

            //删除原用户头像
            Utils.DeleteFile(userModel.avatar);
            userModel.avatar = avatar;

            //修改用户头像
            new BLL.users().UpdateField(userModel.id, "avatar='" + userModel.avatar + "'");
            return Json(new { status = 1, msg = "头像上传成功！", avatar = userModel.avatar });
        }
        #endregion
        #region 修改登录密码
        [HttpPost]
        public IHttpActionResult user_password_edit(string txtOldPassword, string txtPassword)
        {
            int user_id = userModel.id;
            //检查输入的旧密码
            if (string.IsNullOrEmpty(txtOldPassword))
            {
                return Json(new { status = 0, msg = "请输入您的旧登录密码！" });
            }
            //检查输入的新密码
            if (string.IsNullOrEmpty(txtPassword))
            {
                return Json(new { status = 0, msg = "请输入您的新登录密码！" });
            }
            //旧密码是否正确
            if (userModel.password != DESEncrypt.Encrypt(txtOldPassword, userModel.salt))
            {
                return Json(new { status = 0, msg = "对不起，您输入的旧密码不正确！" });
            }
            //执行修改操作
            userModel.password = DESEncrypt.Encrypt(txtPassword, userModel.salt);
            new BLL.users().Update(userModel);
            return Json(new { status = 1, msg = "您的密码已修改成功，请记住新密码！" });
        }
        #endregion
        #region 登录日志列表
        [HttpGet]
        public IHttpActionResult get_user_login_log_list(int limit = 10, int page = 1)
        {
            string strwhere = "user_id=" + userModel.id;
            var list = new BLL.user_login_log().GetQueryPage(page, limit, strwhere, "login_time desc,id desc");
            mr.count = list.TotalItems;
            mr.data = list.Items;
            return Json(mr);
        }
        #endregion
        #region 申请码列表
        [HttpGet]
        public IHttpActionResult get_user_invite_list(int limit = 10, int page = 1)
        {
            string strwhere = "user_name='" + userModel.user_name + "'";
            string _where = "type='" + DTEnums.CodeEnum.Register.ToString() + "'";
            if (!string.IsNullOrEmpty(strwhere))
            {
                _where += " and " + strwhere;
            }
            var list = new BLL.user_code().GetQueryPage(page, limit, _where, "add_time desc,id desc");
            DataTable Items = DataHelper.ListToDataTable(list.Items);
            DataTable oldData = Items.Clone();
            if (list.TotalItems > 0)
            {
                oldData.Columns.Add("status", Type.GetType("System.String"));
                foreach (DataRow item in Items.Rows)
                {
                    DataRow row = oldData.NewRow();
                    row["id"] = item["id"];
                    row["status"] = _base.get_invite_status(item["str_code"].ToString()) ? "有效" : "已失效";
                    row["str_code"] = item["str_code"];
                    row["add_time"] = item["add_time"];
                    row["eff_time"] = item["eff_time"];
                    row["count"] = item["count"];
                    oldData.Rows.Add(row);
                }
            }

            mr.count = list.TotalItems;
            mr.data = oldData;
            return Json(mr);
        }
        #endregion
        #region 申请邀请码
        [HttpPost]
        public IHttpActionResult user_invite_code()
        {
            //检查是否开启邀请注册
            if (userConfig.regstatus != 4)
            {
                return Json(new { status = 0, msg = "对不起，系统不允许通过邀请注册！" });
            }
            BLL.user_code codeBll = new BLL.user_code();
            //检查申请是否超过限制
            if (userConfig.invitecodenum > 0)
            {
                int result = Utils.StrToInt(codeBll.GetCount("count(1)", "user_name='" + userModel.user_name + "' and type='" + DTEnums.CodeEnum.Register.ToString() + "' and datediff(d,add_time,getdate())=0"));
                if (result >= userConfig.invitecodenum)
                {
                    return Json(new { status = 0, msg = "对不起，您申请邀请码的数量已超过每天限制！" });
                }
            }
            //删除过期的邀请码
            codeBll.Delete("type='" + DTEnums.CodeEnum.Register.ToString() + "' and status=1 or datediff(d,eff_time,getdate())>0");
            //随机取得邀请码
            string str_code = Utils.GetCheckCode(8);
            Model.user_code codeModel = new Model.user_code();
            codeModel.user_id = userModel.id;
            codeModel.user_name = userModel.user_name;
            codeModel.type = DTEnums.CodeEnum.Register.ToString();
            codeModel.str_code = str_code;
            codeModel.user_ip = DTRequest.GetIP();
            if (userConfig.invitecodeexpired > 0)
            {
                codeModel.eff_time = DateTime.Now.AddDays(userConfig.invitecodeexpired);
            }
            else
            {
                codeModel.eff_time = DateTime.Now.AddDays(1);
            }
            codeBll.Add(codeModel);
            return Json(new { status = 1, msg = "恭喜您，申请邀请码已成功！" });
        }
        #endregion
        #region 通用外理方法
        #region 校检手机验证码
        private string verify_sms_code(string strcode)
        {
            if (string.IsNullOrEmpty(strcode))
            {
                return "对不起，请输入验证码！";
            }
            if (System.Web.HttpContext.Current.Session[DTKeys.SESSION_SMS_CODE] == null)
            {
                return "对不起，验证码超时或已过期！";
            }
            if (strcode.ToLower() != (System.Web.HttpContext.Current.Session[DTKeys.SESSION_SMS_CODE].ToString()).ToLower())
            {
                return "您输入的验证码与系统的不一致！";
            }
            System.Web.HttpContext.Current.Session[DTKeys.SESSION_SMS_CODE] = null;
            return "success";
        }
        #endregion
        #region 邀请注册处理方法
        private string verify_invite_reg(string user_name, string invite_code)
        {
            if (string.IsNullOrEmpty(invite_code))
            {
                return "邀请码不能为空！";
            }
            BLL.user_code codeBll = new BLL.user_code();
            Model.user_code codeModel = codeBll.GetModel(invite_code);
            if (codeModel == null)
            {
                return "邀请码不正确或已过期！";
            }
            if (userConfig.invitecodecount > 0)
            {
                if (codeModel.count >= userConfig.invitecodecount)
                {
                    codeModel.status = 1;
                    return "该邀请码已经被使用！";
                }
            }
            //检查是否给邀请人增加积分
            if (userConfig.pointinvitenum > 0)
            {
                new BLL.user_point_log().Add(codeModel.user_id, codeModel.user_name, userConfig.pointinvitenum, "邀请用户【" + user_name + "】注册获得积分");
            }
            //更改邀请码状态
            codeModel.count += 1;
            codeBll.Update(codeModel);
            return "success";
        }
        #endregion
        #region 发送手机短信验证码
        private string send_verify_sms_code(string mobile)
        {
            //检查手机
            if (string.IsNullOrEmpty(mobile))
            {
                return "发送失败，请填写手机号码！";
            }
            //检查是否过期
            string cookie = Utils.GetCookie(DTKeys.COOKIE_USER_MOBILE);
            if (cookie == mobile)
            {
                return "time";
            }
            Model.sms_template smsModel = new BLL.sms_template().GetModel(new { call_index = "usercode" }); //取得短信内容
            if (smsModel == null)
            {
                return "发送失败，短信模板不存在，请联系管理员！";
            }
            string strcode = Utils.Number(4); //随机验证码
            //替换标签
            string msgContent = smsModel.content;
            msgContent = msgContent.Replace("{webname}", siteConfig.webname);
            msgContent = msgContent.Replace("{weburl}", siteConfig.weburl);
            msgContent = msgContent.Replace("{webtel}", siteConfig.webtel);
            msgContent = msgContent.Replace("{code}", strcode);
            msgContent = msgContent.Replace("{valid}", userConfig.regsmsexpired.ToString());
            //发送短信
            string tipMsg = string.Empty;
            bool result = SmsFactory.Sms().Send(mobile, smsModel.templateId, 1, msgContent, out tipMsg);
            if (!result)
            {
                return "发送失败，" + tipMsg;
            }
            //写入SESSION，保存验证码
            System.Web.HttpContext.Current.Session[DTKeys.SESSION_SMS_CODE] = strcode;
            Utils.WriteCookie(DTKeys.COOKIE_USER_MOBILE, mobile, userConfig.regsmsexpired); //规定时间内无重复发送
            return "success";
        }
        #endregion
        #region Email验证发送邮件
        private string send_verify_email(string site, Model.users userModel)
        {
            //生成随机码
            string strcode = Utils.GetCheckCode(20);
            BLL.user_code codeBll = new BLL.user_code();
            Model.user_code codeModel;
            //检查是否重复提交
            codeModel = codeBll.GetModel(userModel.user_name, DTEnums.CodeEnum.RegVerify.ToString(), "d");
            if (codeModel == null)
            {
                codeModel = new Model.user_code();
                codeModel.user_id = userModel.id;
                codeModel.user_name = userModel.user_name;
                codeModel.type = DTEnums.CodeEnum.RegVerify.ToString();
                codeModel.str_code = strcode;
                codeModel.eff_time = DateTime.Now.AddDays(userConfig.regemailexpired);
                codeModel.add_time = DateTime.Now;
                new BLL.user_code().Add(codeModel);
            }
            //获得邮件内容
            Model.mail_template mailModel = new BLL.mail_template().GetModel(new { call_index = "regverify" });
            if (mailModel == null)
            {
                return "邮件发送失败，邮件模板内容不存在！";
            }
            //替换模板内容
            string titletxt = mailModel.maill_title;
            string bodytxt = mailModel.content;
            titletxt = titletxt.Replace("{webname}", siteConfig.webname);
            titletxt = titletxt.Replace("{username}", userModel.user_name);
            bodytxt = bodytxt.Replace("{webname}", siteConfig.webname);
            bodytxt = bodytxt.Replace("{webtel}", siteConfig.webtel);
            bodytxt = bodytxt.Replace("{weburl}", siteConfig.weburl);
            bodytxt = bodytxt.Replace("{username}", userModel.user_name);
            bodytxt = bodytxt.Replace("{valid}", userConfig.regemailexpired.ToString());
            bodytxt = bodytxt.Replace("{linkurl}", "http://" + Request.RequestUri.Authority.ToLower() + _base.getlink(site, _base.linkurl("register", "?action=checkmail&code=" + codeModel.str_code)));
            //发送邮件
            try
            {
                DTMail.sendMail(siteConfig.emailport, siteConfig.emailsmtp, siteConfig.emailssl, siteConfig.emailusername, DESEncrypt.Decrypt(siteConfig.emailpassword, siteConfig.sysencryptstring), siteConfig.emailnickname, siteConfig.emailfrom, userModel.email, titletxt, bodytxt);
            }
            catch
            {
                return "邮件发送失败，请联系本站管理员！";
            }
            return "success";
        }
        #endregion
        #endregion END通用方法
        #region 站内消息
        [HttpGet]
        public IHttpActionResult get_user_message_list(string action, int limit = 10, int page = 1)
        {
            string strWhere = string.Empty;
            if (action == "system")
            {
                strWhere = "accept_user_name='" + userModel.user_name + "' and type=1";
            }
            else if (action == "accept")
            {
                strWhere = "accept_user_name='" + userModel.user_name + "' and type=2";
            }
            else if (action == "send")
            {
                strWhere = "post_user_name='" + userModel.user_name + "' and type=3";
            }
            else if (action == "index")
            {
                strWhere = "accept_user_name='" + userModel.user_name + "' and (type=1 or type=2)";
            }
            else
            {
                mr.code = 1;
                mr.msg = "参数传递错误！";
                return Json(mr);
            }
            var list = new BLL.user_message().GetQueryPage(page, limit, strWhere, "is_read asc,post_time desc");
            DataTable Items = DataHelper.ListToDataTable(list.Items);
            DataTable oldData = Items.Clone();
            oldData.Columns.Add("img_url", Type.GetType("System.String"));
            if (list.TotalItems > 0)
            {
                oldData.Columns.Add("img_url", Type.GetType("System.String"));
                foreach (DataRow item in Items.Rows)
                {
                    DataRow row = oldData.NewRow();
                    row["id"] = item["id"];
                    row["type"] = item["type"];
                    row["post_user_name"] = item["post_user_name"];
                    row["accept_user_name"] = item["accept_user_name"];
                    row["is_read"] = item["is_read"];
                    row["title"] = item["title"];
                    row["post_time"] = item["post_time"];
                    row["read_time"] = item["read_time"];
                    if (action == "accept")
                    {
                        row["img_url"] = _base.get_user_avatar(item["post_user_name"].ToString());
                    }
                    else if (action == "send")
                    {
                        row["img_url"] = _base.get_user_avatar(item["accept_user_name"].ToString());
                    }
                    else
                    {
                        row["img_url"] = "";
                    }
                    oldData.Rows.Add(row);
                }
            }

            mr.count = list.TotalItems;
            mr.data = oldData;
            return Json(mr);
        }

        #region 发布站内短消息
        [HttpPost]
        public IHttpActionResult user_message_add(string imgcodeid, string codeindex, string sendSave, string txtUserName, string txtTitle, string txtContent)
        {
            string user_name = Utils.ToHtml(txtUserName);
            string title = Utils.ToHtml(txtTitle);
            string content = Utils.ToHtml(txtContent);
            //校检验证码
            string result = verify_code(imgcodeid, codeindex);
            if (result != "success")
            {
                return Json(new { status = 0, msg = result });
            }
            //检查用户名
            if (string.IsNullOrEmpty(user_name) || !new BLL.users().Exists(user_name))
            {
                return Json(new { status = 0, msg = "对不起，该用户不存在或已删除！" });
            }
            //检查标题
            if (string.IsNullOrEmpty(title))
            {
                return Json(new { status = 0, msg = "对不起，请输入短消息标题！" });
            }
            //检查内容
            if (string.IsNullOrEmpty(content))
            {
                return Json(new { status = 0, msg = "对不起，请输入短消息内容！" });
            }
            //保存数据
            Model.user_message modelMessage = new Model.user_message();
            modelMessage.type = 2;
            modelMessage.post_user_name = userModel.user_name;
            modelMessage.accept_user_name = user_name;
            modelMessage.title = title;
            modelMessage.content = Utils.ToHtml(content);
            new BLL.user_message().Add(modelMessage);
            if (sendSave == "true") //保存到收件箱
            {
                modelMessage.type = 3;
                new BLL.user_message().Add(modelMessage);
            }
            return Json(new { status = 1, msg = "发布短信息成功！" });
        }
        #endregion

        #region 删除短消息
        [HttpDelete]
        public IHttpActionResult user_message_delete(string checkId)
        {
            if (string.IsNullOrEmpty(checkId))
            {
                return Json(new { status = 0, msg = "删除失败，请检查传输参数！" });
            }
            string[] arrId = checkId.Split(',');
            for (int i = 0; i < arrId.Length; i++)
            {
                int id = Utils.StrToInt(arrId[i], 0);
                if (id > 0)
                {
                    new BLL.user_message().Delete(id, userModel.user_name);
                }
            }
            return Json(new { status = 1, msg = "删除短消息成功！" });
        }
        #endregion
        #endregion
        #region 积分
        #region 用户兑换积分
        [HttpPost]
        public IHttpActionResult user_point_convert(int txtAmount, string txtPassword)
        {
            //检查系统是否启用兑换积分功能
            if (userConfig.pointcashrate == 0)
            {
                return Json(new { status = 0, msg = "对不起，网站未开启兑换积分功能！" });
            }
            if (userModel.amount < 1)
            {
                return Json(new { status = 0, msg = "对不起，您账户上的余额不足！" });
            }
            if (txtAmount < 1)
            {
                return Json(new { status = 0, msg = "对不起，最小兑换金额为1元！" });
            }
            if (txtAmount > userModel.amount)
            {
                return Json(new { status = 0, msg = "对不起，您兑换的金额大于账户余额！" });
            }
            if (txtPassword == "")
            {
                return Json(new { status = 0, msg = "对不起，请输入您账户的密码！" });
            }
            //验证密码
            if (DESEncrypt.Encrypt(txtPassword, userModel.salt) != userModel.password)
            {
                return Json(new { status = 0, msg = "对不起，您输入的密码不正确！" });
            }
            //计算兑换后的积分值
            int convertPoint = (int)(Convert.ToDecimal(txtAmount) * userConfig.pointcashrate);
            //扣除金额
            int amountNewId = new BLL.user_amount_log().Add(userModel.id, userModel.user_name, txtAmount * -1, "用户兑换积分");
            //增加积分
            if (amountNewId < 1)
            {
                return Json(new { status = 0, msg = "转换过程中发生错误，请重新提交！" });
            }
            int pointNewId = new BLL.user_point_log().Add(userModel.id, userModel.user_name, convertPoint, "用户兑换积分");
            if (pointNewId < 1)
            {
                //返还金额
                new BLL.user_amount_log().Add(userModel.id, userModel.user_name, txtAmount, "用户兑换积分失败，返还金额");
                return Json(new { status = 0, msg = "转换过程中发生错误，请重新提交！" });
            }
            return Json(new { status = 1, msg = "恭喜您，积分兑换成功！" });
        }
        #endregion
        #region 积分明细列表
        [HttpGet]
        public IHttpActionResult get_user_point_list(string keyword = "", int limit = 10, int page = 1)
        {
            var list = new BLL.user_point_log().GetQueryPage(page, limit, "user_id=" + userModel.id, "add_time desc,id desc");
            mr.data = list.Items;
            mr.count = list.TotalItems;
            return Json(mr);
        }
        #endregion
        #region 删除用户积分明细
        [HttpPost]
        public IHttpActionResult user_point_delete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.user_point_log bll = new BLL.user_point_log();
            foreach (int id in ids)
            {
                if (bll.Delete(id, userModel.user_name))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            return Json(new { status = 1, msg = "积分明细删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }
        #endregion
        #endregion
        #region 收支明细
        #region 收支明细列表
        [HttpGet]
        public IHttpActionResult get_user_amount_list(int limit = 10, int page = 1)
        {
            var list = new BLL.user_amount_log().GetQueryPage(page, limit, "user_id=" + userModel.id, "add_time desc,id desc");
            mr.data = list.Items;
            mr.count = list.TotalItems;
            return Json(mr);
        }
        #endregion
        #region 删除用户收支明细
        [HttpPost]
        public IHttpActionResult user_amount_delete(string checkId)
        {
            if (string.IsNullOrEmpty(checkId))
            {
                return Json(new { status = 0, msg = "删除失败，请检查传输参数！" });
            }
            string[] arrId = checkId.Split(',');
            for (int i = 0; i < arrId.Length; i++)
            {
                int id = Utils.StrToInt(arrId[i], 0);
                if (id > 0)
                {
                    new BLL.user_amount_log().Delete(id, userModel.user_name);
                }
            }
            return Json(new { status = 1, msg = "收支明细删除成功！" });
        }
        #endregion
        #endregion
        #region 充值
        #region 用户在线充值
        /// <summary>
        /// 用户在线充值
        /// </summary>
        /// <param name="site_id">站点ID</param>
        /// <param name="order_amount">充值金额/积分</param>
        /// <param name="action">充值类型</param>
        /// <param name="payment_id">充值方式</param>
        /// <param name="shu">充值金额/积分或充值卡</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult user_amount_recharge(string shu = "", int site_id = 0, int action = 0, int payment_id = 0)
        {
            string sitepath = new BLL.sites().GetBuildPath(site_id); //站点目录
            //检查站点目录
            if (string.IsNullOrEmpty(sitepath))
            {
                return Json(new { status = 0, msg = "错误提示：站点传输参数不正确！" });
            }
            if (payment_id == 100 && string.IsNullOrEmpty(shu))
            {
                return Json(new { status = 0, msg = "对不起，请输入正确的充值卡卡号！" });
            }
            if (action == 0)
            {
                return Json(new { status = 0, msg = "对不起，请选择正确的充值类型！" });
            }
            if (payment_id == 0)
            {
                return Json(new { status = 0, msg = "对不起，请选择正确的支付方式！" });
            }

            #region 充值卡充值

            #endregion
            int amount = Utils.StrToInt(shu);
            if (amount == 0)
            {
                return Json(new { status = 0, msg = "对不起，请输入正确的充值金额！" });
            }
            if (new BLL.payment().Get(payment_id) == null)
            {
                return Json(new { status = 0, msg = "对不起，支付方式不存在或已删除！" });
            }

            //生成订单号
            string order_no = "R" + Utils.GetOrderNumber(); //订单号R开头为充值订单
            new BLL.user_recharge().Add(userModel.id, userModel.user_name, order_no, payment_id, amount);
            //保存成功后返回订单号
            return Json(new { status = 1, msg = "订单保存成功！", url = _base.getlink(sitepath, _base.linkurl("payment", "?action=confirm&order_no=" + order_no)) });
        }
        #endregion
        #region 删除用户充值记录
        [HttpPost]
        public IHttpActionResult user_recharge_delete(string checkId)
        {
            if (string.IsNullOrEmpty(checkId))
            {
                return Json(new { status = 0, msg = "删除失败，请检查传输参数！" });
            }
            string[] arrId = checkId.Split(',');
            for (int i = 0; i < arrId.Length; i++)
            {
                int id = Utils.StrToInt(arrId[i], 0);
                if (id > 0)
                {
                    new BLL.user_recharge().Delete(id, userModel.user_name);
                }
            }
            return Json(new { status = 1, msg = "充值记录删除成功！" });
        }
        #endregion
        #region 充值列表
        [HttpGet]
        public IHttpActionResult get_user_recharge_list(int limit = 10, int page = 1)
        {
            var list = new BLL.user_recharge().GetQueryPage(page, limit, "user_id=" + userModel.id, "add_time desc,id desc");
            DataTable oldData = new DataTable();
            oldData.Columns.Add("id", Type.GetType("System.Int32"));
            oldData.Columns.Add("recharge_no", Type.GetType("System.String"));
            oldData.Columns.Add("add_time", Type.GetType("System.String"));
            oldData.Columns.Add("amount", Type.GetType("System.String"));
            oldData.Columns.Add("status", Type.GetType("System.Int32"));
            oldData.Columns.Add("complete_time", Type.GetType("System.String"));
            oldData.Columns.Add("payment", Type.GetType("System.String"));
            if (list.TotalItems > 0)
            {
                foreach (var item in list.Items)
                {
                    DataRow row = oldData.NewRow();
                    row["id"] = item.id;
                    row["recharge_no"] = item.recharge_no;
                    row["add_time"] = item.add_time;
                    row["amount"] = item.amount;
                    row["status"] = item.status;
                    row["complete_time"] = item.complete_time;
                    row["payment"] = new BLL.site_payment().GetTitle(item.payment_id);
                    oldData.Rows.Add(row);
                }
            }
            mr.data = oldData;
            mr.count = list.TotalItems;
            return Json(mr);
        }
        #endregion
        #endregion
        #region 收货地址
        #region 收货地址列表
        [HttpGet]
        public IHttpActionResult get_addr_book_list(int limit = 10, int page = 1)
        {
            var list = new BLL.user_addr_book().GetQueryPage(page, limit, "user_id=" + userModel.id, "id desc");
            mr.data = list.Items;
            mr.count = list.TotalItems;
            return Json(mr);
        }
        #endregion
        #region 编辑用户收货地址
        [HttpPost]
        public IHttpActionResult user_address_edit(string imgcodeid, string codeindex, string txtAcceptName, string txtProvince, string txtCity, string txtArea, string txtAddress, string txtMobile, string txtTelphone, string txtEmail, string txtPostCode, int id = 0)
        {
            //检查用户是否登录
            Model.user_addr_book model = new Model.user_addr_book();
            BLL.user_addr_book bll = new BLL.user_addr_book();

            if (id > 0)
            {
                if (!bll.Exists(id, userModel.user_name))
                {
                    return Json(new { status = 0, msg = "对不起，收货地址不存在或已删除！" });
                }
                model = bll.Get(id);
            }

            //校检验证码
            string result = verify_code(imgcodeid, codeindex);
            if (result != "success")
            {
                return Json(new { status = 0, msg = result });
            }
            //检查收件人
            if (string.IsNullOrEmpty(txtAcceptName))
            {
                return Json(new { status = 0, msg = "对不起，请输入收件人姓名！" });
            }
            //检查省市区
            if (string.IsNullOrEmpty(txtProvince) || string.IsNullOrEmpty(txtCity) || string.IsNullOrEmpty(txtArea))
            {
                return Json(new { status = 0, msg = "对不起，请选择您所在的省市区！" });
            }
            //检查手机
            if (string.IsNullOrEmpty(txtMobile))
            {
                return Json(new { status = 0, msg = "对不起，请输入收件人的手机！" });
            }
            //保存数据
            model.user_id = userModel.id;
            model.user_name = userModel.user_name;
            model.accept_name = txtAcceptName;
            model.area = txtProvince + "," + txtCity + "," + txtArea;
            model.address = txtAddress;
            model.mobile = txtMobile;
            model.telphone = txtTelphone;
            model.email = txtEmail;
            model.post_code = txtPostCode;
            if (id > 0)
            {
                bll.Update(model);
                return Json(new { status = 1, msg = "修改收货地址成功！" });
            }
            else
            {
                bll.Add(model);
                return Json(new { status = 1, msg = "新增收货地址成功！" });
            }
        }
        #endregion
        #region 用户设置默认收货地址
        [HttpGet]
        public IHttpActionResult user_address_default(int id = 0)
        {
            BLL.user_addr_book bll = new BLL.user_addr_book();
            if (bll.Exists(id, userModel.user_name))
            {
                bll.SetDefault(id, userModel.user_name);
                return Json(new { status = 1, msg = "默认收货地址设置成功！" });
            }
            return Json(new { status = 0, msg = "对不起，该记录不存在或已删除！" });
        }
        #endregion
        #region 删除用户收货地址
        [HttpPost]
        public IHttpActionResult user_address_delete(string checkId)
        {
            if (string.IsNullOrEmpty(checkId))
            {
                return Json(new { status = 0, msg = "删除失败，请检查传输参数！" });
            }
            string[] arrId = checkId.Split(',');
            for (int i = 0; i < arrId.Length; i++)
            {
                int id = Utils.StrToInt(arrId[i], 0);
                if (id > 0)
                {
                    new BLL.user_addr_book().Delete(id, userModel.user_name);
                }
            }
            return Json(new { status = 1, msg = "删除收货地址成功！" });
        }
        #endregion
        #endregion
        #region 我的评论列表
        [HttpGet]
        public IHttpActionResult get_user_comment_list(int limit = 10, int page = 1)
        {
            string strwhere = "user_id=" + userModel.id;
            var list = new BLL.article_comment().GetQueryPage(page, limit, strwhere, "add_time desc,id desc");
            //创建一个DataTable
            DataTable oldData = new DataTable();
            oldData.Columns.Add("id", Type.GetType("System.Int32"));
            oldData.Columns.Add("title", Type.GetType("System.String"));
            oldData.Columns.Add("content", Type.GetType("System.String"));
            oldData.Columns.Add("desc", Type.GetType("System.String"));
            oldData.Columns.Add("add_time", Type.GetType("System.String"));
            oldData.Columns.Add("link", Type.GetType("System.String"));
            oldData.Columns.Add("xianhua", Type.GetType("System.Int32"));
            oldData.Columns.Add("is_lock", Type.GetType("System.Int32"));
            oldData.Columns.Add("is_reply", Type.GetType("System.Int32"));
            oldData.Columns.Add("reply_content", Type.GetType("System.String"));
            oldData.Columns.Add("reply_time", Type.GetType("System.String"));
            if (list.TotalItems > 0)
            {
                foreach (var item in list.Items)
                {
                    DataRow row = oldData.NewRow();
                    row["id"] = item.id;
                    row["title"] = _base.get_article_title(item.channel_id, item.article_id);
                    row["link"] = _base.get_url_rewrite(item.channel_id, "", item.article_id);
                    row["content"] = Utils.ToTxt(item.content);
                    row["desc"] = item.system + " " + item.browser;
                    row["add_time"] = item.add_time.ToString("yyyy-MM-dd HH:mm:ss");
                    row["xianhua"] = item.xianhua;
                    row["is_lock"] = item.is_lock;
                    row["is_reply"] = item.is_reply;
                    row["reply_content"] = item.reply_content;
                    row["reply_time"] = item.reply_time;
                    oldData.Rows.Add(row);
                }
            }

            mr.count = list.TotalItems;
            mr.data = oldData;
            return Json(mr);
        }
        #endregion
    }
}
